package com.hbl.cgs.cgsagent.plugin;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.hbl.cgs.cgsagent.Utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PluginManager {
    private final Map<String, Plugin> allPlugins;
    private final Map<String, Plugin> startedPlugins;
    private final Map<String, Plugin> stoppedPlugins;

    private final PluginFactory pluginFactory;

    public PluginManager() {
        allPlugins = new HashMap<>();
        startedPlugins = new HashMap<>();
        stoppedPlugins = new HashMap<>();

        pluginFactory = new DefaultPluginFactory();
    }

    public synchronized void loadPlugins() throws PluginConfigException  {
        InputStream pluginConfigStream = null;
        try {
            List<String> pluginConfigPaths = Utils.getPluginsConfigPath();
            for (String pluginConfigPath : pluginConfigPaths) {
                pluginConfigStream = new FileInputStream(pluginConfigPath);
                ObjectMapper mapper = new ObjectMapper();
                ArrayNode pluginNodes = (ArrayNode) mapper.readTree(pluginConfigStream);
                for (JsonNode pluginNode : pluginNodes) {
                    Plugin plugin = pluginFactory.create(pluginNode);
                    register(plugin);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (pluginConfigStream != null) {
                    pluginConfigStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void register(Plugin plugin) {
        if (allPlugins.containsKey(plugin.getName())) {
            return;
        }
        allPlugins.put(plugin.getName(), plugin);
        stoppedPlugins.put(plugin.getName(), plugin);
    }
}
